<?php

namespace App\Http\Controllers;

use App\Blog;
use App\User;
use Illuminate\Http\Request;
use Auth;
class BlogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
//        //找到id等于4的博客内容
//        $blog = Blog::find(4);
//        //如果想获取被关联的数据,就把关联方法当成属性使用
//        dd($blog->user->toArray());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
//        //获取post数据
//        $post = $request->all();
//        //往post数据中加入作者
//        $post['uid'] = Auth::user()->id;
//        Blog::create($post);
        //使用模型关联方法添加blog数据
        //获取post数据
        $post = $request->all();
        //获取当前已经登录的用户数据
        //如果需要调用关联来进行添加,修改等操作,就要把关联方法当成方法来使用
        $user = Auth::user();
        $user->blog()->create($post);
        //设置闪存并跳转
        session()->flash('success','博客发布成功');
        return redirect('/');

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function show(Blog $blog)
    {
        //加载博客内容模板
        return view('blog.show',compact('blog'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function edit(Blog $blog)
    {
        //通过权限策略判断是否有权限编辑博客内容
        $this->authorize('update',$blog);
        //加载编辑博客模板
        return view('blog.edit',compact('blog'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Blog $blog)
    {
        $blog->content = $request->input('content');
        $blog->save();
        session()->flash('success','博客内容编辑成功');
        return redirect('/');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Blog  $blog
     * @return \Illuminate\Http\Response
     */
    public function destroy(Blog $blog)
    {
        $blog->delete();
        session()->flash('success','博客内容删除成功');
        return back();
    }
}
